<template>
    <div class="userinfo-container">
        <el-form ref="userFormRef" :model="userForm" :rules="modifyUserInfoRules" :hide-required-asterisk="true">
            <el-form-item label="账号" prop="account">
                <el-input v-model="userForm.account" readonly style="width:450px;"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="username">
                <el-input v-model="userForm.username" maxlength="64" show-word-limit style="width:450px;"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="modifyUserInfo">保 存</el-button>
            </el-form-item>
        </el-form>
        <el-row>
            <el-button type="warning" plain @click="modifyDialogVisible = true">修改密码</el-button>
        </el-row>

        <el-dialog v-model="modifyDialogVisible" title="修改密码" width="350" center :destroy-on-close="true"
            :close="handleClose()">
            <el-form ref="formRef" :model="form" :rules="modifyPasswordRules">
                <el-form-item class="form-item" prop="oldPassword">
                    <el-input v-model="form.oldPassword" type="password" autocomplete="off" show-password
                        placeholder="请输入旧密码">
                        <template #prefix>
                            <i class="iconfont icon-mima" />
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item class="form-item" prop="newPassword">
                    <el-input v-model="form.newPassword" type="password" autocomplete="off" show-password
                        placeholder="请输入新密码">
                        <template #prefix>
                            <i class="iconfont icon-mima" />
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item class="form-item" prop="confirmPassword">
                    <el-input v-model="form.confirmPassword" type="password" autocomplete="off" show-password
                        placeholder="请确认新密码">
                        <template #prefix>
                            <i class="iconfont icon-mima" />
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="modifyDialogVisible = false" type="danger">取消</el-button>
                    <el-button type="primary" @click="modifyPassword">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { sha256 } from 'js-sha256'
import { ref } from 'vue'
import { modifyPasswordAPI, modifyUserInfoAPI } from '@/apis/user'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

// 修改密码对话框是否可见
const modifyDialogVisible = ref(false)

const userFormRef = ref(null)
// 修改个人信息
const userForm = ref({
    account: userStore.userInfo.account,
    username: userStore.userInfo.username,
})

// 修改个人信息规则
const modifyUserInfoRules = {
    username: [
        { required: true, message: '用户名不能为空', trigger: 'change' }
    ]
}

function modifyUserInfo() {
    // 调用表单实例验证方法
    userFormRef.value.validate(async (valid) => {
        // valid：所有表单都通过校验才为true
        if (valid) {
            let formData = new FormData()
            formData.append("username", userForm.value.username)
            modifyUserInfoAPI(formData).then((res) => {
                if (res.code === 0) {
                    // 请求成功
                    userStore.getUserInfo().then((ret) => {
                        if (ret.code === 0) {
                            ElMessage({ type: "success", message: "保存成功" })
                        } else {
                            ElMessage({ type: "success", message: ret.message })
                        }
                    })
                } else {
                    ElMessage({ type: "error", message: res.message })
                }
            }).catch(() => {
                ElMessage({ type: "error", message: "保存失败" })
            })
        }
    })
}

// 修改密码信息
const form = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
})

const formRef = ref(null) // 表单对象实例


// 修改密码规则
const modifyPasswordRules = {
    oldPassword: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, max: 128, message: '密码长度不能小于6', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, max: 128, message: '密码长度不能小于6', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: "确认密码不能为空", trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== form.value.newPassword) {
                    callback(new Error("两次密码不一致"))
                } else {
                    callback()
                }
            }
        }
    ],
}

function modifyPassword() {
    // 调用表单实例验证方法
    formRef.value.validate(async (valid) => {
        // valid：所有表单都通过校验才为true
        if (valid) {
            const oldPassword = sha256(form.value.oldPassword)
            const newPassword = sha256(form.value.newPassword)
            console.log(oldPassword)
            modifyPasswordAPI({ oldPassword, newPassword }).then((res) => {
                if (res.code === 0) {
                    // 修改成功
                    ElMessage({ type: "success", message: "修改成功" })
                    modifyDialogVisible.value = false
                } else {
                    // 修改失败
                    ElMessage({ type: "error", message: res.message })
                }
            }).catch(() => {
                ElMessage({ type: "error", message: "修改失败" })
            })
        }
    })
}

// 关闭修改对话框后清空内容
function handleClose() {
    form.value.oldPassword = ''
    form.value.newPassword = ''
    form.value.confirmPassword = ''
}

</script>

<style scoped lang="scss">
.userinfo-container {
    padding: 0 100px;
    height: 600px;
}

.form-item {
    width: 320px;
    padding: 0 15px;
}
</style>